#! /bin/bash
echo "系统用户列表:"
getent passwd|grep  "/bin/bash"|awk -F: '{print $1}'>/tmp/system_user.txt
cat /tmp/system_user.txt
echo '查看AllowUsers列表:'
AllowUsers=`grep "AllowUsers" /etc/ssh/sshd_config`
echo $AllowUsers
user_str=''
function all_ip()
{
if [ -z "$AllowUsers" ];then
   echo "创建AllowUsers字段"
   while read line
     do
       echo "授权$line"
       user_str="$user_str $line"
     done < /tmp/system_user.txt
   echo "AllowUsers $user_str" >> /etc/ssh/sshd_config
else
   echo "AllowUsers字段已存在"
   while read line
     do
       if [[ "$AllowUsers" =~ "$line" ]];then
          echo "$line已授权过，不再重复授权"
       else
          echo "授权$line"
          user_str="$user_str $line"
       fi
     done < /tmp/system_user.txt
    sed -i "s/$AllowUsers/$AllowUsers$user_str/g" /etc/ssh/sshd_config
fi
}
function one_ip()
{
echo "堡垒机ip: "$jms_ip
if [ -z "$AllowUsers" ];then
   echo "创建AllowUsers字段"
   while read line
     do
       echo "授权$line"
       user_str="$user_str $line@"$jms_ip
     done < /tmp/system_user.txt
     echo "AllowUsers $user_str" >> /etc/ssh/sshd_config
else
   echo "AllowUsers字段已存在"
   while read line
     do
       if [[ "$AllowUsers" =~ "$line" ]];then
          echo "$line已授权过了，不再重复授权"
       else
          echo "授权$line"
          user_str="$user_str $line@"$jms_ip
       fi
     done < /tmp/system_user.txt
     sed -i "s/$AllowUsers/$AllowUsers$user_str/g" /etc/ssh/sshd_config
fi
}
function test1()
{
echo "test1"$jms_ip
}
if [ "$1" == "all_ip" ];then
   echo $1
   all_ip
   systemctl reload sshd
elif [ "$1" == "one_ip" ];then
   echo $1
   jms_ip=$2
   echo ${jms_ip}
   if [ "${jms_ip}" != "" ];then
      one_ip $jms_ip
      systemctl reload sshd
   else
      echo "one_ip 选项须指定ip"
   fi
else
   echo "参数请输入:all_ip|one_ip ip"
fi